﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ERP_RORZE_PERMISSION.Base;
using ERP_RORZE_PERMISSION.Base.Objects;

namespace ERP_RORZE_PERMISSION.Forms
{
    public partial class frm_Login : DevExpress.XtraEditors.XtraForm
    {
        private string userName;
        private LogUtils log;

        public frm_Login()
        {
            InitializeComponent();
            this.errorLabel.Visible = false;
            this.userName = GetUserName();
            log = new LogUtils();
        }

        private void frm_Login_Load(object sender, EventArgs e)
        {
            this.txtUser.Text = userName;
            Utilities.WriteToFile(PermissionConstants.FileName, Utilities.Encrypt(PermissionConstants.PasswordHash, PermissionConstants.SaltKey, PermissionConstants.VIKey, this.userName));

        }

        private void btAdd_Click(object sender, EventArgs e)
        {
            string pass = Utilities.EncryptPassword(txtPass.Text, PermissionConstants.Key);
            if (Permission.CheckLogin(txtUser.Text, txtPass.Text))
            {

                //write Log
                log.Table = LogConstant.Table.SystemAdmin.Users;
                log.Task = LogConstant.Task.Login;
                log.Username = txtUser.Text;
                log.Description =txtUser.Text + " logged in successfully.";
                log.WriteLog();

                this.errorLabel.Visible = false;
                string text = Utilities.Encrypt(PermissionConstants.PasswordHash, PermissionConstants.SaltKey, PermissionConstants.VIKey, txtUser.Text) + "\n" + Utilities.Encrypt(PermissionConstants.PasswordHash, PermissionConstants.SaltKey, PermissionConstants.VIKey, pass);
                Utilities.WriteToFile(PermissionConstants.FileName, text);
                this.Dispose();
            }
            else
            {
                //MessageBox.Show("Sai Tên đăng nhập hoặc Mật khẩu.");
                this.errorLabel.Visible = true;
                this.txtUser.Text = "";
                this.txtPass.Text = "";
                this.txtUser.Focus();
            }
        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();

            //Utilities.ReadFromFile(Permission.FileName);
        }

        private string GetUserName()
        {
            string userName = "";
            string[] temp = Utilities.ReadFromFile(PermissionConstants.FileName);
            userName = Utilities.Decrypt(PermissionConstants.PasswordHash, PermissionConstants.SaltKey, PermissionConstants.VIKey, temp[0]);


            return userName;
        }
    }
}